package com.example.myapplication3;

import android.app.Activity;
import android.app.ProgressDialog;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.widget.Button;

public class progress_dialog extends Activity {
    // 数据填充相关
    private final int[] data = new int[100];
    private int hasData = 0;

    // 进度条配置
    private static final int MAX_PROGRESS = 100;
    private ProgressDialog progressDialog;
    private int currentProgress = 0;

    // 线程通信
    private final Handler handler = new Handler(Looper.getMainLooper()) {
        @Override
        public void handleMessage(Message msg) {
            if (msg.what == 1 && progressDialog != null) {
                progressDialog.setProgress(currentProgress); // 安全更新进度
                if (currentProgress >= MAX_PROGRESS) {
                    progressDialog.dismiss(); // 完成后自动关闭
                }
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_progress_dialog);

        Button startButton = findViewById(R.id.btn_start_progress);
        startButton.setOnClickListener(v -> showProgressDialog());
    }

    private void showProgressDialog() {
        // 初始化对话框
        progressDialog = new ProgressDialog(this);
        progressDialog.setTitle("任务进度");
        progressDialog.setMessage("正在加载，请稍候...");
        progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        progressDialog.setMax(MAX_PROGRESS);
        progressDialog.setCancelable(false);
        progressDialog.show();

        // 启动后台任务
        new Thread(() -> {
            try {
                while (currentProgress < MAX_PROGRESS) {
                    currentProgress = simulateWork(); // 模拟耗时操作
                    handler.sendEmptyMessage(1); // 发送更新信号
                    Thread.sleep(100); // 控制更新频率
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                // 确保对话框最终关闭
                runOnUiThread(() -> {
                    if (progressDialog != null && progressDialog.isShowing()) {
                        progressDialog.dismiss();
                    }
                });
            }
        }).start();
    }

    private int simulateWork() {
        // 模拟填充数据
        if (hasData < data.length) {
            data[hasData] = (int) (Math.random() * 100);
            hasData++;
        }
        return hasData; // 返回当前进度
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        // 防止内存泄漏
        if (progressDialog != null && progressDialog.isShowing()) {
            progressDialog.dismiss();
            progressDialog = null;
        }
    }
}